package com.jeesite.modules.utils;

import com.paypal.core.PayPalEnvironment;
import com.paypal.core.PayPalHttpClient;
import com.paypal.orders.*;
import com.paypal.http.HttpResponse;
import com.jeesite.modules.config.PaymentConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * PayPal工具类 - 真实SDK实现
 * @author LaVenderGong
 * @version 2025-08-16
 */
@Component
public class PaypalUtil {
    
    @Autowired
    private PaymentConfig paymentConfig;
    
    private PayPalHttpClient paypalClient;
    
    /**
     * 获取PayPal客户端
     * 懒加载模式，第一次使用时初始化
     */
    private PayPalHttpClient getPaypalClient() {
        if (paypalClient == null) {
            PaymentConfig.Paypal config = paymentConfig.getPaypal();
            
            // 根据模式选择环境
            PayPalEnvironment environment;
            if ("live".equals(config.getMode())) {
                // 生产环境
                environment = new PayPalEnvironment.Live(
                    config.getClientId(),
                    config.getClientSecret()
                );
            } else {
                // 沙箱环境
                environment = new PayPalEnvironment.Sandbox(
                    config.getClientId(),
                    config.getClientSecret()
                );
            }
            
            // 创建PayPal客户端
            paypalClient = new PayPalHttpClient(environment);
        }
        return paypalClient;
    }
    
    /**
     * 创建PayPal支付订单
     * @param orderId 订单号
     * @param amount 支付金额（美元）
     * @param description 商品描述
     * @return 支付结果，包含支付链接
     */
    public Map<String, Object> createPayment(String orderId, String amount, String description) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            PaymentConfig.Paypal config = paymentConfig.getPaypal();
            
            // 创建订单请求
            OrderRequest orderRequest = new OrderRequest();
            
            // 设置支付意图
            orderRequest.checkoutPaymentIntent("CAPTURE");  // 立即捕获支付
            
            // 设置应用上下文（回调地址等）
            ApplicationContext applicationContext = new ApplicationContext()
                .returnUrl(config.getReturnUrl())    // 支付成功跳转地址
                .cancelUrl(config.getCancelUrl())    // 支付取消跳转地址
                .brandName("KBB服务器")               // 品牌名称
                .landingPage("BILLING")              // 登录页面类型
                .userAction("PAY_NOW");              // 用户操作类型
            
            orderRequest.applicationContext(applicationContext);
            
            // 设置购买单元
            List<PurchaseUnitRequest> purchaseUnits = new ArrayList<>();
            PurchaseUnitRequest purchaseUnit = new PurchaseUnitRequest()
                .referenceId(orderId)                // 商户订单号
                .description(description)            // 订单描述
                .customId(orderId)                   // 自定义ID
                .softDescriptor("KBB捐赠")           // 软描述符
                .amountWithBreakdown(new AmountWithBreakdown()
                    .currencyCode("USD")             // 货币代码
                    .value(amount)                   // 金额
                    .amountBreakdown(new AmountBreakdown()
                        .itemTotal(new Money()
                            .currencyCode("USD")
                            .value(amount)
                        )
                    )
                )
                .items(List.of(
                    new Item()
                        .name("KBB服务器捐赠")        // 商品名称
                        .description(description)     // 商品描述
                        .sku(orderId)                 // 商品SKU
                        .unitAmount(new Money()
                            .currencyCode("USD")
                            .value(amount)
                        )
                        .quantity("1")                // 数量
                        .category("DIGITAL_GOODS")    // 商品类别
                ));
            
            purchaseUnits.add(purchaseUnit);
            orderRequest.purchaseUnits(purchaseUnits);
            
            // 创建订单请求
            OrdersCreateRequest request = new OrdersCreateRequest();
            request.prefer("return=representation");  // 返回完整的订单信息
            request.requestBody(orderRequest);
            
            // 执行请求
            HttpResponse<Order> response = getPaypalClient().execute(request);
            
            if (response.statusCode() == 201) {
                // 订单创建成功
                Order order = response.result();
                
                // 查找支付链接
                String approvalUrl = null;
                for (LinkDescription link : order.links()) {
                    if ("approve".equals(link.rel())) {
                        approvalUrl = link.href();
                        break;
                    }
                }
                
                if (approvalUrl != null) {
                    result.put("success", true);
                    result.put("approvalUrl", approvalUrl);     // 支付链接
                    result.put("orderId", orderId);
                    result.put("paypalOrderId", order.id());    // PayPal订单ID
                    result.put("message", "PayPal订单创建成功");
                } else {
                    result.put("success", false);
                    result.put("message", "未找到PayPal支付链接");
                }
            } else {
                // 订单创建失败
                result.put("success", false);
                result.put("message", "创建PayPal订单失败，状态码: " + response.statusCode());
            }
            
        } catch (Exception e) {
            // 异常处理
            result.put("success", false);
            result.put("message", "创建PayPal订单失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 捕获PayPal支付
     * @param paypalOrderId PayPal订单ID
     * @return 捕获结果
     */
    public Map<String, Object> capturePayment(String paypalOrderId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建捕获请求
            OrdersCaptureRequest request = new OrdersCaptureRequest(paypalOrderId);
            request.prefer("return=representation");
            request.requestBody(new OrderActionRequest());
            
            // 执行捕获
            HttpResponse<Order> response = getPaypalClient().execute(request);
            
            if (response.statusCode() == 201) {
                // 捕获成功
                Order order = response.result();
                
                result.put("success", true);
                result.put("orderId", order.id());
                result.put("status", order.status());
                result.put("message", "PayPal支付捕获成功");
                
                // 获取捕获详情
                if (order.purchaseUnits() != null && !order.purchaseUnits().isEmpty()) {
                    PurchaseUnit purchaseUnit = order.purchaseUnits().get(0);
                    if (purchaseUnit.payments() != null && 
                        purchaseUnit.payments().captures() != null && 
                        !purchaseUnit.payments().captures().isEmpty()) {
                        
                        Capture capture = purchaseUnit.payments().captures().get(0);
                        result.put("captureId", capture.id());
                        result.put("amount", capture.amount().value());
                        result.put("currency", capture.amount().currencyCode());
                    }
                }
            } else {
                // 捕获失败
                result.put("success", false);
                result.put("message", "PayPal支付捕获失败，状态码: " + response.statusCode());
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "PayPal支付捕获失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 查询PayPal订单状态
     * @param paypalOrderId PayPal订单ID
     * @return 查询结果
     */
    public Map<String, Object> queryOrderStatus(String paypalOrderId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建查询请求
            OrdersGetRequest request = new OrdersGetRequest(paypalOrderId);
            
            // 执行查询
            HttpResponse<Order> response = getPaypalClient().execute(request);
            
            if (response.statusCode() == 200) {
                // 查询成功
                Order order = response.result();
                
                result.put("success", true);
                result.put("orderId", order.id());
                result.put("status", order.status());           // 订单状态
                result.put("intent", order.checkoutPaymentIntent());           // 支付意图
                result.put("createTime", order.createTime());   // 创建时间
                result.put("updateTime", order.updateTime());   // 更新时间
                
                // 获取金额信息
                if (order.purchaseUnits() != null && !order.purchaseUnits().isEmpty()) {
                    PurchaseUnit purchaseUnit = order.purchaseUnits().get(0);
                    AmountWithBreakdown amount = purchaseUnit.amountWithBreakdown();
                    if (amount != null) {
                        result.put("amount", amount.value());
                        result.put("currency", amount.currencyCode());
                    }
                }
            } else {
                // 查询失败
                result.put("success", false);
                result.put("message", "查询PayPal订单失败，状态码: " + response.statusCode());
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询PayPal订单失败: " + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 验证PayPal回调
     * @param callbackData 回调数据
     * @return 验证结果
     */
    public boolean verifyCallback(Map<String, Object> callbackData) {
        try {
            // PayPal的回调验证通常通过HTTPS和证书来保证安全性
            // 这里可以添加额外的验证逻辑，比如：
            // 1. 验证回调来源IP
            // 2. 验证订单金额
            // 3. 验证订单状态
            
            // 基本验证：检查必要字段是否存在
            return callbackData.containsKey("id") &&           // 订单ID
                   callbackData.containsKey("status") &&       // 订单状态
                   callbackData.containsKey("intent");         // 支付意图
                   
        } catch (Exception e) {
            System.err.println("PayPal回调验证失败: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 检查PayPal配置是否完整
     * @return 配置检查结果
     */
    public boolean checkConfig() {
        try {
            PaymentConfig.Paypal config = paymentConfig.getPaypal();
            
            // 检查必要配置项
            return config.getClientId() != null && !config.getClientId().isEmpty() &&
                   config.getClientSecret() != null && !config.getClientSecret().isEmpty() &&
                   config.getMode() != null && !config.getMode().isEmpty() &&
                   config.getReturnUrl() != null && !config.getReturnUrl().isEmpty() &&
                   config.getCancelUrl() != null && !config.getCancelUrl().isEmpty();
                   
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 将人民币转换为美元（简化实现）
     * @param cnyAmount 人民币金额
     * @return 美元金额
     */
    public String convertCnyToUsd(String cnyAmount) {
        try {
            // 简化的汇率转换，实际项目中应该调用实时汇率API
            double cny = Double.parseDouble(cnyAmount);
            double usd = cny / 7.2;  // 假设汇率为1美元=7.2人民币
            return String.format("%.2f", usd);
        } catch (Exception e) {
            return "1.00";  // 默认值
        }
    }
}
